package com.cdutetc.websocketTest.handler;


import java.io.IOException;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import lombok.RequiredArgsConstructor;
@Component
public class DataWebSocketHandler extends TextWebSocketHandler{
    private final CopyOnWriteArrayList<WebSocketSession> sessions = new CopyOnWriteArrayList<>();
    // 描述ws的基本方法
    // afterConnectionEstablished
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception{
        // 当新的WebSocket连接建立时调用
        // 将新的会话添加到会话列表中
        sessions.add(session);
        System.out.println("New WebSocket connection established: " + session.getId());
        sendData(session, "连接成功，等待数据。。。。。");
    }
    // 处理来自客户端的文本消息
    @Override
    public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception{
        // 处理接收到的文本消息
        String payload = message.getPayload();
        System.out.println("Received message: " + payload + " from session: " + session.getId());
    }

    // 连接关闭时调用
    @Override
    public void afterConnectionClosed(WebSocketSession session,CloseStatus status)throws Exception{
        // 当WebSocket连接关闭时调用
        // 从会话列表中移除关闭的会话
        sessions.remove(session);
        System.out.println("WebSocket connection closed: " + session.getId());
    }
    // 广播数据给所有连接的客户端
    public void broadcastData(String data){
        TextMessage message = new TextMessage(data);
        for(WebSocketSession session:sessions){
            try {
                session.sendMessage(message);
                System.out.println("sent data to session:"+session.getId()+",data:"+data);
            } catch (IOException e) {
                System.err.println("error sending data"+session.getId()+":"+e.getMessage());
            }
        }
    }
    // 发送数据给特定的客户端
    private void sendData(WebSocketSession session,String data)throws IOException{
        session.sendMessage(new TextMessage(data));
        System.out.println("sent data to session:"+session.getId()+",data:"+data);
    }
}
